import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket Socket = null;
    private String severIP;
    private int severport;

    //客户端不需要显式的绑定端口,在启动客户端时需要知道服务器在哪
    public UdpEchoClient(String severIP,int severport) throws SocketException {
        Socket = new DatagramSocket();
        this.severIP=severIP;
        this.severport=severport;
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        //与服务器多次交互
        while(true){
            //1.读取请求字符串
            //2.字符串构造为UDP packet，并发送
            //3.尝试读取返回的响应
            //4.响应数据转为String并展示出来~
            System.out.println("->");
            String request = scanner.next();

            DatagramPacket requestPacket = new DatagramPacket (request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(severIP),severport);//分开设置IP和端口
            Socket.send(requestPacket);

            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            Socket.receive(responsePacket);

            String response = new String(responsePacket.getData(),0, responsePacket.getLength());
            System.out.printf("req:%s,resp:%s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);//本机ip
        udpEchoClient.start();
    }
}
